package com.suntront.lib_db;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.suntront.lib_db.config.MyDbConfig;
import com.suntront.lib_db.dao.ErrorTDao;
import com.suntront.lib_db.dao.MeterDao;
import com.suntront.lib_db.dao.TestDao;
import com.suntront.lib_db.dao.UserDao;
import com.suntront.lib_db.table.ErrorT;
import com.suntront.lib_db.table.MeterT;
import com.suntront.lib_db.table.MeterTDownLoadUpdate;
import com.suntront.lib_db.table.NewsT;
import com.suntront.lib_db.table.Test;
import com.suntront.lib_db.table.UserT;

/**
 * 数据库管理
 */
@Database(entities = {
        Test.class,
        MeterT.class,
        ErrorT.class,
        UserT.class,
        NewsT.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    //
    public abstract TestDao testDao();

    public abstract ErrorTDao errorTDao();

    public abstract MeterDao meterDao();

    public abstract UserDao userDao();

    /**
     * 初始化
     * dbPath 如果是在内存卡，需先申请内存卡读写权限
     *
     * @return
     */
    private static volatile AppDatabase database;

    public static AppDatabase instance(Context context) {
        if (database == null) {
            synchronized (AppDatabase.class) {
                if (database == null) {
                    database = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, MyDbConfig.dbPath)
                            .allowMainThreadQueries()//允许在主线程查询数据
//                            .addMigrations()//迁移数据库使用
//                            .fallbackToDestructiveMigration()//迁移数据库如果发生错误，将会重新创建数据库，而不是发生崩溃
                            .build();
                }
            }
        }
        return database;
    }

    public static AppDatabase getDb() {
        return database;
    }

    public static void closeDb() {
        if (database != null && database.isOpen()) {
            database.close();
        }
    }

    //数据库升级 1 - 2
    static Migration migration = new Migration(1, 2) {
        @Override
        public void migrate(SupportSQLiteDatabase database) {
            database.execSQL("ALTER TABLE Userjava " + " ADD COLUMN address TEXT");
        }
    };
}
